<template>
  <el-dropdown @command="handleCommand">
    <span class="user-info">
      <el-avatar :size="30" :src="userStore.avatar" />
      <span class="user-name">{{ userStore.name }}</span>
      <el-icon><arrow-down /></el-icon>
    </span>

    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="profile">
          <el-icon><user /></el-icon>
          个人中心
        </el-dropdown-item>
        <el-dropdown-item command="settings">
          <el-icon><setting /></el-icon>
          设置
        </el-dropdown-item>
        <el-dropdown-item divided command="logout">
          <el-icon><switch-button /></el-icon>
          退出登录
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { removeToken } from '@/utils/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Setting,
  SwitchButton,
  ArrowDown
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

const handleCommand = (command) => {
  switch (command) {
    case 'logout':
      handleLogout()
      break
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
  }
}

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logout().then(() => {
      removeToken()
      router.push('/login')
      ElMessage.success('退出成功')
    })
  }).catch(() => {
    ElMessage.info('已取消退出')
  })
}
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;

  .user-name {
    margin: 0 10px;
    font-size: 14px;
  }
}
</style>